package com.example.myapplication;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class Fragment2_ChatActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private Fragment2_ChatAdapter chatAdapter;
    private List<Fragment2_Message> messageList;
    private EditText editTextMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_2_activity_chat);

        recyclerView = findViewById(R.id.recyclerViewChat);
        editTextMessage = findViewById(R.id.editTextMessage);
        Button buttonSend = findViewById(R.id.buttonSend);

        messageList = new ArrayList<>();
        chatAdapter = new Fragment2_ChatAdapter(messageList);
        recyclerView.setAdapter(chatAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        buttonSend.setOnClickListener(v -> {
            String messageContent = editTextMessage.getText().toString();
            if (!messageContent.isEmpty()) {
                sendMessage(messageContent);
                editTextMessage.setText(""); // 清空输入框
            }
        });
    }

    private void sendMessage(String messageContent) {
        Fragment2_Message newMessage = new Fragment2_Message(messageContent, true); // true 表示由用户发送
        messageList.add(newMessage);
        chatAdapter.notifyItemInserted(messageList.size() - 1);
        recyclerView.scrollToPosition(messageList.size() - 1); // 滚动到最后一条消息
    }
}